package com.hoshiicloud.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.update.UpdateBatchParam;
import com.hoshiicloud.goods.dto.sku.SkuDTO;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.feign.IdGeneratorService;
import com.hoshiicloud.goods.mapper.sku.ExtSkuMapper;
import com.hoshiicloud.goods.param.ListSkuSpuParam;
import com.hoshiicloud.goods.service.ExtSkuService;
import com.hoshiicloud.goods.vo.ListSpuSkuVo;
import com.hoshiicloud.goods.vo.StoreAndBaseSkuIdsVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 扩展商品SKU 服务实现类
 * </p>
 * 2019-06-04 zhangshuhu
 */
@Slf4j
@Service
public class ExtSkuServiceImpl extends ServiceImpl<ExtSkuMapper, ExtSku> implements ExtSkuService {
    private final IdGeneratorService idGeneratorService;
    private final ExtSkuMapper extSkuMapper;

    public ExtSkuServiceImpl(IdGeneratorService idGeneratorService, ExtSkuMapper extSkuMapper) {
        this.idGeneratorService = idGeneratorService;
        this.extSkuMapper = extSkuMapper;
    }

    @Override
    @Logable(authName = "商品管理-扩展商品SKU管理-分页查询扩展商品SKU")
    @Cacheable(cacheNames = "ExtSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public Page<ExtSku> getPage(Page<ExtSku> page,QueryWrapper <ExtSku> queryWrapper, String key) {
        baseMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    @Logable(authName = "商品管理-扩展商品SKU管理-查询扩展商品SKU列表")
    @Cacheable(cacheNames = "ExtSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public List<ExtSku> listByParam(QueryWrapper<ExtSku> queryWrapper, String key) {
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * @param id
     * @return ExtSku
     * @description: 根据id查询扩展商品SKU
     */
    @Override
    @Cacheable(cacheNames = "ExtSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "商品管理-扩展商品SKU-查询扩展商品SKU ")
    public ExtSku getById(Long id) {
        return baseMapper.selectById(id);
    }


    /**
     * @param entity
     * @return boolean
     * @description: 新增扩展商品SKU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSku", allEntries = true)
    @Logable(authName = "商品管理-扩展商品SKU-新增扩展商品SKU")
    public boolean save(ExtSku entity) {

        // 生成主键ID
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return true;
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改扩展商品SKU
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSku", allEntries = true)
    @Logable(authName = "商品管理-扩展商品SKU管理-修改扩展商品SKU")
    public boolean updateById(ExtSku entity) {

        // 更新数据
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }




    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "ExtSku", allEntries = true)
    @Logable(authName = "商品管理-扩展商品SKU管理-删除扩展商品SKU")
    public boolean deleteById(Long id) {

        // 根据id查询数据
        ExtSku entity = this.getById(id);
        if (entity == null) {
            log.error("删除扩展商品SKU异常，无法找到扩展商品SKU记录");
            throw new ServiceException("删除扩展商品SKU异常，无法找到扩展商品SKU记录");
        }

        //进行删除操作
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setDeleted(1);
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        }
        return true;
    }

    @Override
    @Cacheable(cacheNames = "ExtSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-扩展商品SKU管理-根据id集合查询扩展商品SKU")
    public List<ExtSku> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    /**
     * 查询扩展商品sku信息及库存
     *
     * @param wrapper
     * @return
     */
    @Override
    public List<SkuDTO> listSKuStockByIds(Wrapper<ExtSku> wrapper) {
        return baseMapper.listSKuStockByIds(wrapper);
    }

    /**
     * 新增分店 ExtSku
     */
    @Override
    @CacheEvict(cacheNames = "ExtSku", allEntries = true)
    public ExtSku saveExtSku(ExtSku entity) {
        // 生成主键ID
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("新增失败"));
        }

        // 新增数据
        entity.setId(Long.parseLong(id));
        entity.setCreatedTime(LocalDateTime.now());
        int row = baseMapper.insert(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return entity;
    }

    /**
     * 根据spuid获取sku最低价
     *
     * @param wrapper 查询参数
     * @return Map<String, Object>
     */
    @Cacheable(cacheNames = "ExtSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#wrapper.entity.spuId")
    @Logable(authName = "商品管理-扩展商品SKU管理-根据spuid获取sku最低价")
    @Override
    public Map<String, Object> listSkuMiniPrice(Wrapper<ExtSku> wrapper) {
        return extSkuMapper.listSkuMiniPrice(wrapper);
    }

    /**
     * 批量上下架ExtSku
     */
    @Override
    @CacheEvict(cacheNames = "ExtSku", allEntries = true)
    public Boolean ExtSkuShelvesUpAndDown(List<ExtSku> extSkus, Integer status, String message) {

        // 判断 ExtSku 是否存在, 如果不存在就不用做下架操作
        if (extSkus.isEmpty()) {
            return true;
        }

        // 设置ExtSpu上下架信息
        extSkus.stream().forEach(extSku -> {
            extSku.setStatus(status);
            extSku.setUpdatedTime(LocalDateTime.now());
        });

        // 批量更新
        boolean isSpuShelvesUpOrDown = this.updateBatchById(extSkus);
        if (!isSpuShelvesUpOrDown) {
            throw new ServiceException(message + "失败");
        }
        return true;
    }




    @Override
    @Cacheable(cacheNames = "ExtSku", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "商品管理-扩展商品SKU管理-根据店铺ID查询店铺的sku分配数量")
    public Map<String, String> getStoreSkuNum(List<Long> storeIds, String key) {
        QueryWrapper<ExtSku> q = new QueryWrapper<>();
        q.select("store_id as storeId", "count(id) as dispatchPolicy");
        q.lambda().eq(ExtSku::getDeleted, 0)
                .in(ExtSku::getStoreId, storeIds)
                .groupBy(ExtSku::getStoreId);
        List<ExtSku> list = baseMapper.selectList(q);
        Map<String, String> map = new HashMap<>();
        if (list.size() == 0) {
            for (Long storeId : storeIds) {
                map.put(storeId.toString(), "0");
            }
        } else {
            Map<String, String> map2 = new HashMap<>();
            for (ExtSku p : list) {
                map2.put(p.getStoreId().toString(), p.getDispatchPolicy().toString());
            }
            for (Long storeId : storeIds) {
                map.put(storeId.toString(), map2.getOrDefault(storeId.toString(), "0"));
            }
        }
        return map;
    }


    @Override
    @Logable(authName = "商品管理-扩展商品SKU管理-根据storeId 获取base_sku_id")
    public Map<String, List<String>> queryStoresAndBaseSkuIds(List<Long> storeIds, String key) {
        QueryWrapper<ExtSku> q = new QueryWrapper<>();
        q.lambda().in(ExtSku::getStoreId, storeIds);
        Map<String, List<String>> map = new HashMap<>();
        List<StoreAndBaseSkuIdsVo> rs = baseMapper.listStoreAndBaseSkuIds(q);

        if (CollectionUtils.isNotEmpty(rs)) {
            for (StoreAndBaseSkuIdsVo s : rs) {
                map.put(s.getStoreId(), s.getBaseSkuIds());
            }
        } else {
            for (Long s : storeIds) {
                map.put(s.toString(), new ArrayList<>());
            }
        }
        return map;
    }

    @Override
    @CacheEvict(cacheNames = "ExtSku", allEntries = true)
    @Logable(authName = "商品管理-扩展商品SKU管理-批量保存")
    public Boolean saveBatch1(List<ExtSku> list) {
        return this.saveBatch(list);
    }

    @CacheEvict(cacheNames = "ExtSku", allEntries = true)
    @Logable(authName = "根据自定义条件批量更新")
    @Override
    public boolean updateBatchByWrapper(UpdateBatchParam<ExtSku> updateBatchParam) {
        ExtSku updateEntity = updateBatchParam.getUpdateEntity();
        UpdateWrapper<ExtSku> updateWrapper = updateBatchParam.getUpdateWrapper();
        if (updateEntity.getReceiptDate() == null) {
            updateWrapper.lambda().set(ExtSku::getReceiptDate, null);
        }
        return this.update(updateEntity, updateWrapper);
    }

    /**
     * 通用的更新操作
     */
    @Override
    @CacheEvict(cacheNames = "ExtSku", allEntries = true)
    @Logable(authName = "批量更新")
    public boolean omniExtSkuUpdate(OmnipotentParam<ExtSku> param) {
        OmnipotentWrapper<ExtSku> omiWrapper = new OmnipotentWrapper<>();
        UpdateWrapper updateWrapper = omiWrapper.getUpdateWrapper(param.getWrappers());
        ExtSku entityUpdate = param.getEntity();
        return this.update(entityUpdate, updateWrapper);
    }

    /**
     * 批量查询
     */
    @Override
    public List<ExtSku> queryBatch(List<OmnipotentWrapper> params) {
        OmnipotentWrapper<ExtSku> wrappers = new OmnipotentWrapper<>();
        QueryWrapper<ExtSku> wrapper = wrappers.getWrapper(params);
        return baseMapper.selectList(wrapper);
    }


    /**
     * 查询扩展商品sku信息及库存
     *
     * @param queryWrapper
     * @return List<SkuDTO>
     */
    @Override
    public List<SkuDTO> headOfficeListSKuStockByIds(QueryWrapper<ExtSku> queryWrapper) {
        return baseMapper.headOfficeListSKuStockByIds(queryWrapper);
    }

    /**
     * 根据分店的skuId查询出总店的id和skuName
     *
     * @param id 分店商品的skuId
     * @return Map
     */
    @Override
    public Map<String, Object> selectSkuNameAndParentId(Long id) {
        return baseMapper.selectSkuNameAndParentId(id);
    }

    @Override
    public Long selectHeadOfficeSkuId(Map<String, Object> maps) {
        return baseMapper.selectHeadOfficeSkuId(maps);
    }



    @Override
    public Page<ListSpuSkuVo> getBranchStoreCanAddSkuPage(ListSkuSpuParam param) {
        Page<ListSpuSkuVo> page = new Page<>(Long.valueOf(param.getPageNumber()),Long.valueOf(param.getPageSize()));
        baseMapper.getBranchStoreCanAddSkuPage(page,param);
        return page;
    }


}
